import { _decorator, Component, lerp, Node, v3, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('TraceCamera')
export class TraceCamera extends Component {

    public static Instance: TraceCamera = null;

    // 跟随速度，越接近1越快
    @property
    followSpeed: number = 0.1;

    public IsTrace: boolean = false;
    public Target: Node = null;
    private _initPos: Vec3 = new Vec3();

    protected onLoad(): void {
        TraceCamera.Instance = this;

        this._initPos = this.node.getWorldPosition().clone();
    }

    protected update(dt: number): void {
        if (!this.IsTrace) return;
        // if (this.Target) {
        //     const targetPos: Vec3 = this.Target.getWorldPosition().clone();
        //     this.node.setWorldPosition(v3(targetPos.x, targetPos.y, this._initPos.z));
        // }

        if (this.Target) {
            // 获取目标位置（目标在移动）
            const targetPos: Vec3 = this.Target.worldPosition;

            // 保持Z不变
            const desiredPos = v3(targetPos.x, targetPos.y, this._initPos.z);

            // 当前相机位置
            const currentPos = this.node.worldPosition;

            // 线性插值 (lerp) 让相机慢慢靠近目标
            const newPos = v3(
                lerp(currentPos.x, desiredPos.x, this.followSpeed),
                lerp(currentPos.y, desiredPos.y, this.followSpeed),
                lerp(currentPos.z, desiredPos.z, this.followSpeed)
            );

            this.node.setWorldPosition(newPos);
        }
    }

    public trace(target: Node) {
        this.Target = target;
        this.IsTrace = true;
    }

    public free() {
        this.Target = null;
        this.IsTrace = false;
        this.node.setWorldPosition(this._initPos);
    }
}


